from selenium import webdriver
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import getpass


def open_browser(browser: str = "chrome"):
	"""
	打开浏览器的方法
	:param browser: 浏览器
	:return: 浏览器本身
	"""
	if browser.lower() == "chrome":
		return webdriver.Chrome()
	elif browser.lower() == "firefox":
		return webdriver.Firefox()
	elif browser.lower() == "edge":
		return webdriver.Edge()
	else:
		print("请输入合法的浏览器名称,例如(chrome,firefox,edge)")
		return None


def avoid_the_login_chrome(username: str = ""):
	"""
	谷歌浏览器加载项配置,实现网站免登录
	:param username: 本机用户名
	:return: 浏览器本身
	"""
	if username == "":
		username = getpass.getuser()
	# 找到个人资料路径
	user_data_dir = fr'--user-data-dir=C:\Users\{username}\AppData\Local\Google\Chrome\User Data'
	# 配置谷歌浏览器加载项
	options = webdriver.ChromeOptions()
	options.add_argument(user_data_dir)
	# 带着加载项启动谷歌浏览器
	return webdriver.Chrome(options=options)


class Base(object):
	def __init__(self, driver):
		self.driver = driver

	def open_url(self, url):
		"""
		访问网址
		:param url: 访问的地址
		:return:
		"""
		self.driver.get(url)
		self.driver.maximize_window()

	def find_element(self, locator: tuple, timeout=5):
		"""
		定位一个元素
		:param locator:定位器
		:param timeout:超时时间
		:return:元素
		"""
		try:
			return WebDriverWait(self.driver, timeout).until(EC.presence_of_element_located(locator))
		except:
			print(f'元素{locator}没找到')
			return False

	def find_elements(self, locator: tuple, timeout=5):
		"""
		定位一个元素
		:param locator: 定位器
		:param timeout: 超时时间
		:return: 元素
		"""
		try:
			return WebDriverWait(self.driver, timeout).until(EC.presence_of_all_elements_located(locator))
		except:
			print(f'元素{locator}没找到')
			return False

	def send_keys(self, text, locator: tuple = (), element="", timeout=5):
		"""
		输入文本值
		:param text: 文本值
		:param element: 元素
		:param locator: 定位器
		:param timeout: 超时时间
		:return:
		"""
		if element == "":
			element = self.find_element(locator, timeout)
		if element is not False:
			element.send_keys(text)
		else:
			print(f'元素{locator}定位失败,无法输入')

	def click(self, locator: tuple, timeout=5):
		"""
		点击元素
		:param locator: 定位器
		:param timeout: 超时时间
		:return:
		"""
		element = self.find_element(locator, timeout)
		if element is not False:
			element.click()
		else:
			print(f'元素{locator}定位失败,无法点击')

	def select(self, locator: tuple = (), element="", timeout=5, value="", index: int = -1, text: str = ""):
		"""
		下拉框
		:param element: 元素
		:param text: 文本值
		:param index: 索引
		:param value: value值
		:param locator: 定位器
		:param timeout: 超时时间
		:return:
		"""
		if element == "":
			element = self.find_element(locator, timeout)
		if element is not False:
			select = Select(element)
			if value != "" and index == -1 and text == "":
				select.select_by_value(str(value))
			elif value == "" and index != -1 and text == "":
				select.select_by_index(index)
			elif value == "" and index == -1 and text != "":
				select.select_by_visible_text(text)
			else:
				print("请传入有且仅有一个参数:value/index/text")
		else:
			print(f'元素{locator}定位失败,无法选择下拉框')

	def radio_button(self, locator: tuple, is_selected=0, timeout=5):
		"""
		单选框
		:param timeout: 超时时间
		:param locator: 定位器
		:param is_selected: 是否勾选,默认不勾选
		:return:
		"""
		if int(is_selected) == 0:
			is_selected = False
		elif int(is_selected) == 1:
			is_selected = True
		else:
			print("请传入正确的数据(0-False/1-True)")
		element = self.find_element(locator, timeout)
		if is_selected is True:
			if not element.is_selected():
				self.click(locator, timeout)
		else:
			if element.is_selected():
				self.click(locator, timeout)

	def checkbox(self, attribute: str, value_list: list, locator: tuple, timeout=5):
		"""
		复选框
		:param attribute: 属性
		:param value_list: 勾选的数据
		:param timeout: 超时时间
		:param locator: 定位器
		:return:
		"""
		elements = self.find_elements(locator, timeout)
		for element in elements:  # 遍历复选框元素列表
			if element.get_attribute(attribute) in value_list:  # 从列表中过滤需要勾选的选项
				if not element.is_selected():
					element.click()
			else:
				if element.is_selected():  # 对不选择的选项进行判断
					element.click()

	def is_text_equal_in_element(self, text, locator: tuple, timeout=5):
		"""
		判断给定的文本值是否和元素的文本值相等
		:param text: 给定的文本内容
		:param locator: 定位器
		:param timeout: 超时时间
		:return: 相等返回True,否则返回False
		"""
		element = self.find_element(locator, timeout)
		if element is not False:
			return element.text == text
		else:
			print(f'元素{locator}没找到,无法比较')
			return False

	def switch_to_frame(self, param):
		"""
		进入iframe
		:param param: 参数,可以传id/name值/标签元素/索引值
		:return:
		"""
		self.driver.switch_to.frame(param)

	def switch_to_parent_frame(self):
		"""退出到上一层frame"""
		self.driver.switch_to.parent_frame()

	def switch_to_default_content(self):
		"""直接退出frame"""
		self.driver.switch_to.default_content()

	def execute_script(self, js: str):
		"""执行js代码"""
		self.driver.execute_script(js)

	def capture_alert(self, locator: tuple, timeout=5):
		"""捕获弹窗"""
		# 点击触发弹窗的元素
		self.click(locator=locator, timeout=timeout)
		# 捕获弹窗
		return self.driver.switch_to.alert

	def get_browser_url(self):
		"""
		获取网页链接
		@Author: 何晨辉
		:return: 网页连接
		"""
		return self.driver.url

	def is_link_jump_success(self, url):
		"""
		超链接跳转是否成功
		@Author: 何晨辉
		:param url: 超链接
		:return: True：成功，False：失败
		"""
		# 获取当前网页地址
		browser_url = self.driver.current_url
		if url is not False:
			# 如果地址存在，判断地址是否正确
			return browser_url == url
		else:
			print(f'{url}，当前地址不存在')
			return False

	def back_browser(self):
		"""
		浏览器后退
		:return:
		"""
		self.driver.back()

	def close_browser(self):
		"""
		关闭浏览器
		:return:
		"""
		self.driver.quit()


if __name__ == '__main__':
	import time

	# base = Base(open_browser())
	# base.open_url("https://www.baidu.com/")
	# base.send_keys("selenium自动化", ("id", "kw"))
	# time.sleep(1)
	# base.click(("id", "su"))

	base = Base(avoid_the_login_chrome())
	# base.open_url("http://localhost:8080/ecshop/admin/")
	base.open_url("http://localhost:8080/ecshop/")
	time.sleep(2)
	base.close_browser()
